<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userNickname">
        <el-input
          v-model="queryParams.userNickname"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['orders:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orders:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orders:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderId" />
      <el-table-column label="用户名" align="center" prop="userNickname" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber" />
      <el-table-column label="商品信息" align="center" prop="productName" />
      <el-table-column label="售价" align="center" prop="productPrice" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="实际支付金额" align="center" prop="actualPayment" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" />
      <el-table-column label="订单创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <div class="order-actions">
            <!-- 订单详情按钮 -->
              <el-button   type="text" size="small" @click="handleDetail(scope)">
                <i class="el-icon-document"/> 订单详情
              </el-button>
            <span class="separator">|</span>
            <!-- 更多操作下拉框 -->
            <el-dropdown trigger="click">
              <el-button type="text" size="small">
                更多 <i class="el-icon-more" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleDeliver(scope.row)">
                    <i class="el-icon-truck" /> <text style="color:#7DBDFF ">发货</text>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleCancel(scope.row)">
                    <i class="el-icon-close" /> 取消订单
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(scope.row)">
                    <i class="el-icon-delete" /> <text style="color: red">删除</text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </div>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog
        :title="title"
        v-model="detailDialogVisible"
        width="70%"
        append-to-body>
      <h3>订单状态</h3>
      <el-form  :model="form1" :rules="rules" label-width="80px">
        <el-form-item label="订单状态" prop="orderStatus">
          <el-input v-model="form1.orderStatus" disabled/>
        </el-form-item>
        <el-form-item label="用户昵称" prop="userNickname">
          <el-input v-model="form1.userNickname" disabled/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form1.phoneNumber" disabled/>
        </el-form-item>
        <h3>收货信息</h3>
        <el-form-item label="收货人" prop="userNickname">
          <el-input v-model="form1.userNickname" disabled/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form1.phoneNumber" disabled/>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="form1.address" disabled/>
        </el-form-item>
        <h3>配送信息</h3>
        <el-form-item label="配送方式" prop="companyName">
          <el-input v-model="form1.companyName" disabled/>
        </el-form-item>
        <el-form-item label="快递单号" prop="ems">
          <el-input v-model="form1.ems" disabled/>
        </el-form-item>
        <div v-if="form1.orderStatus=='待收货'" >
          <p style="color: #ed5565">已发货，等待快递员揽收</p>
        </div>
        <div v-if="form1.orderStatus=='已完成'" >
          <p style="color: #ed5565">已签收，已取走包裹</p>
        </div>
      </el-form>


      <h3>商品信息</h3>
      <el-table :data="orderList1" style="width: 80%">
        <el-table-column label="商品照片" align="center" prop="productImage" >
          <template #default="scope">
            <image-preview :src="scope.row.productImage" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="productName" />
        <el-table-column label="商品编号" align="center" prop="productCode" />
        <el-table-column label="商品价格" align="center" prop="productPrice" />
        <el-table-column label="商品数量" align="center" prop="quantity" />
        <el-table-column label="邮费" align="center" prop="emsPrice" />
      </el-table>
      <table style="width: 100%" :data="orderList1">
        <tr>
          <td >商品总额:￥{{totalAmount }}</td>
        </tr>
        <tr>
          <td>邮费:￥{{totalPostage }}</td>
        </tr>
      </table>

        <h3>订单信息</h3>
      <el-form  :model="form1" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form1.orderId" disabled/>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="form1.createTime" disabled/>
        </el-form-item>
      </el-form>


      <template #footer>
        <div style="display: flex; justify-content: center">
          <!-- 取消订单按钮，订单状态为待支付或待发货时显示 -->
          <el-button v-if="form1.orderStatus === '待支付' || form1.orderStatus === '待发货'" type="danger" @click="handleCancel1(form1)">取消订单</el-button>
          <!-- 修改发货信息按钮，订单状态为待发货时显示 -->
          <el-button v-if="form1.orderStatus === '待发货'" type="primary" @click="handleModifyDeliveryInfo(form1)">修改发货信息</el-button>
          <!-- 发货按钮，订单状态为待发货时显示 -->
          <el-button v-if="form1.orderStatus === '待发货'" type="success" @click="handleDeliver1(form1)">发货</el-button>
          <!-- 确认收货按钮，订单状态为待收货时显示 -->
          <el-button v-if="form1.orderStatus === '待收货'" type="warning" @click="handleConfirmReceive(form1)">确认收货</el-button>
          <!-- 删除订单按钮，订单状态为已完成或交易关闭时显示 -->
          <el-button v-if="form1.orderStatus === '已完成' || form1.orderStatus === '交易关闭'" type="danger" @click="handleDeleteOrder(form1)">删除订单</el-button>
          <!-- 返回按钮始终显示 -->
          <el-button type="default" @click="handleReturn">返回</el-button>
        </div>
      </template>
    </el-dialog>

<el-dialog
    :title="title"
    v-model="detailDialogVisible1"
    width="50%"
    append-to-body>
  <el-form ref="orderRef1" :model="form2" :rules="rules" label-width="80px">
    <el-form-item label="收货人" prop="userNickname">
      <el-input v-model="form2.userNickname" />
    </el-form-item>
    <el-form-item label="手机号码" prop="phoneNumber">
      <el-input v-model="form2.phoneNumber" />
    </el-form-item>
    <el-form-item label="详细地址" prop="address">
      <el-input v-model="form2.address" />
    </el-form-item>
  </el-form>

  <template #footer>
    <div style="display: flex; justify-content: center">
      <el-button type="primary" @click="handleAddressUpdate()">确认修改</el-button>
      <el-button type="default" @click="guanbi">返回</el-button>
    </div>
  </template>

</el-dialog>


    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理-vv对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userNickname">
          <el-input v-model="form.userNickname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="商品信息" prop="productName">
          <el-select v-model="form.pId" placeholder="请选择商品" @change="handleProductChange">
            <el-option v-for="product in productList" :key="product.productCode" :label="product.productName" :value="product.productCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售价" prop="productPrice">
          <el-input v-model="form.productPrice" placeholder="请输入售价" @input="calculateActualPayment" disabled />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量"  @input="calculateActualPayment"/>
        </el-form-item>
        <el-form-item label="实际支付金额" prop="actualPayment">
          <el-input v-model="form.actualPayment" placeholder="请输入实际支付金额" disabled />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <!-- 遍历 orderStatusList 渲染下拉选项 -->
            <el-option
                v-for="status in orderStatusList"
                :key="status"
                :label="status"
                :value="status"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送方式" prop="kId">
<!--          <el-input v-model="form.companyName" placeholder="请输入配送方式" />-->
          <el-select v-model="form.kId" placeholder="请选择配送方式" >
          <el-option v-for="option in kindList" :key="option.id" :label="option.companyName" :value="option.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递订单" prop="ems">
          <el-input v-model="form.ems" placeholder="请输入物流单号" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>



</template>

<script setup name="Order">
import {listKind,listProduct, gCities,gProvinces,listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/orders/order"
import { ref, computed ,reactive,onMounted } from 'vue';
import {updateCategoryStatus} from "@/api/info/category.js";
// 商品总额计算
const totalAmount = computed(() => {
  return orderList1.value.reduce((sum, item) => {
    return sum + (item.productPrice * item.quantity || 0);
  }, 0);
});

// 邮费获取（假设列表中每个商品的邮费都相同且取第一个商品的邮费，可根据实际调整）
const totalPostage = computed(() => {
  return orderList1.value.length > 0? orderList1.value[0].emsPrice : 0;
});

const orderStatusList = ['待收货', '待发货', '待支付', '已取消', '已完成'];
const { proxy } = getCurrentInstance()
const orderList = ref([])
const kindList = ref([])
const provinceList=ref([])
const cityList=ref([])
const orderList1 = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const productList = ref([])
const productNames=ref([])
// 控制对话框显示隐藏
const detailDialogVisible   = ref(false);
const form1=ref(reactive({}))
// 假设从后台获取订单详情数据后填充到该对象
const handleDetail = (scope) => {
  form1.value = { ...scope.row };
  console.log(form1.value)
  orderList1.value = [form1.value];
  detailDialogVisible.value = true;
};

const detailDialogVisible1 = ref(false);
const form2=ref ({});
const handleModifyDeliveryInfo = (form1) => {
  form2.value = { ...form1 };
  detailDialogVisible1.value = true;
}
// 计算实际支付金额的方法
const calculateActualPayment = () => {
  const productPrice = parseFloat(form.value.productPrice) || 0
  const quantity = parseFloat(form.value.quantity) || 0
  form.value.actualPayment = (productPrice * quantity).toFixed(2)
}

// const router = useRouter();
// const handleDetail = (scope) => {
//   router.push('@/views/orders/order/detail.vue');
// };


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userNickname: null,
    phoneNumber: null,
    productInfo: null,
    price: null,
    quantity: null,
    actualPayment: null,
    orderStatus: null,
    createTime: null,
    sId: null,
    kId: null,
    mId: null
  },
  rules: {
    userNickname: [
      { required: true, message: "用户名不能为空", trigger: "blur" }
    ],
    phoneNumber: [
      { required: true, message: "手机号码不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "订单创建时间不能为空", trigger: "blur" }
    ],
    sId: [
      { required: true, message: "售后外键不能为空", trigger: "blur" }
    ],
    kId: [
      { required: true, message: "快递外键不能为空", trigger: "blur" }
    ],
    mId: [
      { required: true, message: "成员(外键)不能为空", trigger: "blur" }
    ]
  }
})
// 获取当天的物流单号计数器，如果没有则初始化为 0
const getTodayEmsCounter = () => {
  const today = new Date().toISOString().split('T')[0]
  const storedCounter = localStorage.getItem('emsCounter_' + today)
  return storedCounter? parseInt(storedCounter) : 0
}

// 保存当天的物流单号计数器
const saveTodayEmsCounter = (counter) => {
  const today = new Date().toISOString().split('T')[0]
  localStorage.setItem('emsCounter_' + today, counter.toString())
}

// 生成物流单号
const generateEmsNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  let counter = getTodayEmsCounter()
  counter++
  saveTodayEmsCounter(counter)
  const serialNumber = String(counter).padStart(4, '0')
  return `KD${year}${month}${day}${serialNumber}`
}




const { queryParams, form, rules } = toRefs(data)
// 获取当天的订单计数器，如果没有则初始化为0
const getTodayCounter = () => {
  const today = new Date().toISOString().split('T')[0]
  const storedCounter = localStorage.getItem('orderCounter_' + today)
  return storedCounter? parseInt(storedCounter) : 0
}

// 保存当天的订单计数器
const saveTodayCounter = (counter) => {
  const today = new Date().toISOString().split('T')[0]
  localStorage.setItem('orderCounter_' + today, counter.toString())
}

// 生成订单编号
const generateOrderId = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  let counter = getTodayCounter()
  counter++
  saveTodayCounter(counter)
  const serialNumber = String(counter).padStart(4, '0')
  return `DD${year}${month}${day}${serialNumber}`
}
// 订单详情按钮
function handleConfirmReceive(form1) {
  const deliverData = {
    orderId: form1.orderId,
    orderStatus: "已完成"
  };
  updateOrder(deliverData ).then(response => {
    proxy.$modal.msgSuccess("状态更新成功")
    form1.orderStatus = "已完成";
    getList()
  })
}
function handleCancel1(form1) {
  const deliverData = {
    orderId: form1.orderId,
    orderStatus: "已取消"
  };
  updateOrder(deliverData ).then(response => {
    proxy.$modal.msgSuccess("状态更新成功")
    form1.orderStatus = "已取消";
    getList()
  })
}

onMounted(()=>{
  productList1()
  kind1()
getProvinces()
  getCities()
  console.log("111")
});
function getProvinces() {
  loading.value = true
  gProvinces().then(response => {
    provinceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getCities() {
  loading.value = true
  gCities().then(response => {

  })
}







/** 查询订单管理-vv列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })

}

function productList1() {
  loading.value = true
  listProduct()
      .then(response => {
        console.log('接口返回数据:', response); // 打印接口返回数据，检查是否正确
        productList.value = response
        console.log(productList.value)
        loading.value = false
      })
      .catch(error => {
        console.error('获取商品列表失败:', error);
        loading.value = false
        proxy.$modal.msgError('获取商品列表失败，请稍后重试');
      })
}

function kind1() {
  loading.value = true
  listKind().then(response => {
        console.log('接口返回数据:', response); // 打印接口返回数据，检查是否正确
        kindList.value = response.rows
        console.log(kindList.value)
        loading.value = false
      })
}


// 处理商品选择事件
function handleProductChange(selectedProductCode) {
  console.log('选中的商品代码:', selectedProductCode);
  const selectedProduct = productList.value.find(product => product.productCode === selectedProductCode);
  if (selectedProduct) {
    console.log('找到对应的商品:', selectedProduct);
    form.value.productPrice = selectedProduct.productPrice;
  } else {
    console.log('未找到对应的商品');
    form.value.productPrice = null;
  }
}




console.log(productList.value)

console.log(productNames.value)

// 取消按钮
function handleReturn() {
  detailDialogVisible.value = false
}
function guanbi(){
  detailDialogVisible1.value = false
}
// 表单重置
function reset() {
  form.value = {
    orderId: null,
    userNickname: null,
    phoneNumber: null,
    productInfo: null,
    price: null,
    quantity: null,
    actualPayment: null,
    orderStatus: null,
    createTime: null,
    sId: null,
    kId: null,
    mId: null
  }
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单管理-vv"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getOrder(_orderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单管理-vv"
  })
}

function handleAddressUpdate() {
  proxy.$refs["orderRef1"].validate(valid => {
        updateOrder(form2.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          console.log(form2.value)
          form1.value=form2.value
          form.value=form2.value
          getList()
          detailDialogVisible1.value=false
        })
  })
}

// 取消订单
// handleCancel
function handleCancel(row) {
  const deliverData = {
    orderId: row.orderId,
    orderStatus: "已取消"
  };
  updateOrder(deliverData ).then(response => {
    proxy.$modal.msgSuccess("取消订单成功")
    getList()
  })
}
function handleDeliver(row) {
  if (row.orderStatus === "已取消") {
    // 提示订单已取消，不能发货
    proxy.$modal.msgWarning("该订单已取消，无法进行发货操作")
    return;
  }
  const deliverData = {
    orderId: row.orderId,
    orderStatus: "待收货"
  };
  updateOrder(deliverData ).then(response => {
    proxy.$modal.msgSuccess("状态更新成功")
    getList()
  })
}
function handleDeliver1(form1) {
  if (form1.orderStatus === "已取消") {
    // 提示订单已取消，不能发货
    proxy.$modal.msgWarning("该订单已取消，无法进行发货操作")
    return;
  }
  const deliverData = {
    orderId: form1.orderId,
    orderStatus: "待收货"
  };
  updateOrder(deliverData ).then(response => {
    proxy.$modal.msgSuccess("状态更新成功")
    getList()
    form1.orderStatus = "待收货";
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      // 移除 productPrice 字段
      const { productPrice, ...formData } = form.value;
      if (form.value.orderId != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 新增操作，移除 productPrice 字段
        const { productPrice, ...formData } = form.value;
        const orderId = generateOrderId()
        form.value.orderId = orderId
        // 生成物流单号
        form.value.ems = generateEmsNumber()
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
function handleDeleteOrder(form1) {
  const _orderIds = form1.orderId
  proxy.$modal.confirm('是否确认删除订单管理-vv编号为"' + _orderIds + '"的数据项？').then(function() {
    return delOrder(_orderIds)
  }).then(() => {
    detailDialogVisible.value = false
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除订单管理-vv编号为"' + _orderIds + '"的数据项？').then(function() {
    return delOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orders/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList()
</script>



